<template>
	<view>
		<view class="container">
			<view class="text">
				请拍摄清晰完整的身份证正面照片，系统可以自动识别信息，示例如下：
			</view>
			<view class="image-container">
				<image v-if="preview" :src="preview" mode="widthFix" class="preview" />
				<image v-else src="/static/images/shili.png" mode="widthFix" style="width: 90%;"></image>
			</view>
			<view class="btn" v-if="!isUp" @tap="chooseSource">
				立即拍摄
			</view>
			<view class="btn" @tap="goback" v-else>
				确定
			</view>
		</view>
	</view>
</template>

<script>
export default {
  data() {
    return {
	  isUp:false,
	  preview: '',   // 本地预览图
      uploading: false,
      percent: 0,
	  raceArray: [
	  	{ name: '汉族' }, 
	  	{ name: '壮族' }, 
	  	{ name: '回族' }, 
	  	{ name: '满族' },
	  	{ name: '维吾尔族' },
	  	{ name: '苗族' },
	  	{ name: '彝族' },
	  	{ name: '土家族' },
	  	{ name: '藏族' },
	  	{ name: '蒙古族' },
	  	{ name: '侗族' },
	  	{ name: '布依族' },
	  	{ name: '瑶族' },
	  	{ name: '白族' },
	  	{ name: '朝鲜族' },
	  	{ name: '哈尼族' },
	  	{ name: '黎族' },
	  	{ name: '哈萨克族' },
	  	{ name: '傣族' },
	  	{ name: '畲族' },
	  	{ name: '傈僳族' },
	  	{ name: '东乡族' },
	  	{ name: '仡佬族' },
	  	{ name: '拉祜族' },
	  	{ name: '佤族' },
	  	{ name: '水族' },
	  	{ name: '纳西族' },
	  	{ name: '羌族' },
	  	{ name: '土族' },
	  	{ name: '仫佬族' },
	  	{ name: '锡伯族' },
	  	{ name: '柯尔克孜族' },
	  	{ name: '景颇族' },
	  	{ name: '达斡尔族' },
	  	{ name: '撒拉族' },
	  	{ name: '布朗族' },
	  	{ name: '毛南族' },
	  	{ name: '塔吉克族' },
	  	{ name: '普米族' },
	  	{ name: '阿昌族' },
	  	{ name: '怒族' },
	  	{ name: '鄂温克族' },
	  	{ name: '京族' },
	  	{ name: '基诺族' },
	  	{ name: '德昂族' },
	  	{ name: '保安族' },
	  	{ name: '俄罗斯族' },
	  	{ name: '裕固族' },
	  	{ name: '乌孜别克族' },
	  	{ name: '门巴族' },
	  	{ name: '鄂伦春族' },
	  	{ name: '独龙族' },
	  	{ name: '赫哲族' },
	  	{ name: '高山族' },
	  	{ name: '珞巴族' },
	  	{ name: '塔塔尔族' }
	  ],
    };
  },

  methods: {
    /* 1. 弹出拍照/相册选择 + 权限处理 */
    chooseSource() {
      // 先检查相册/相机权限
      this.checkAuth().then(() => {
        uni.showActionSheet({
          itemList: ['拍照', '从相册选择'],
          success: (res) => {
            const sourceType = res.tapIndex === 0 ? ['camera'] : ['album'];
            this.chooseImage(sourceType);
          }
        });
      });
    },

    /* 2. 统一权限申请（相机+相册） */
    checkAuth() {
      return new Promise((resolve, reject) => {
        uni.getSetting({
          success: (res) => {
            const cameraOk = res.authSetting['scope.camera'];
            const albumOk  = res.authSetting['scope.writePhotosAlbum'];
            // 只要有一个没授权，就都重新授权一遍，避免第二次弹不出来
            const needAuth = [];
            if (cameraOk !== true) needAuth.push('scope.camera');
            if (albumOk  !== true) needAuth.push('scope.writePhotosAlbum');

            if (needAuth.length === 0) return resolve();

            let finishCount = 0;
            needAuth.forEach(scope => {
              uni.authorize({
                scope,
                complete: () => {
                  finishCount++;
                  if (finishCount === needAuth.length) resolve();
                }
              });
            });
          }
        });
      });
    },

    /* 3. 选图 + 压缩 + 上传 */
    chooseImage(sourceType) {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType,
        success: (res) => {
          this.preview = res.tempFilePaths[0];
          this.compressAndUpload(res.tempFilePaths[0]);
		  this.isUp=true
        }
      });
    },

    compressAndUpload(src) {
      uni.compressImage({
        src,
        quality: 80,
        success: (res) => this.uploadImage(res.tempFilePath)
      });
    },

    uploadImage(filePath) {
      this.uploading = true;
      this.percent = 0;
	  var myDate = new Date()
	  var ossPath = 'ueditor/upload/weixin/' + myDate.getFullYear()
	  const imgsrc = filePath;
	  const index = imgsrc.lastIndexOf(".");
	  const imgExtension = imgsrc.substring(index + 1, imgsrc.length);
	  console.log("后缀：" + imgExtension)
	  //  随机生成文件名称
	  var fileRandName = Date.now() + "" + parseInt(Math.random() * 1000)
	  
	  var fileName = fileRandName + '.' + imgExtension
	  // 要提交的key
	  var fileKey = ossPath + '/' + fileName

      uni.uploadFile({
        url: 'https://tuozhen1.oss-cn-beijing.aliyuncs.com/',
        filePath,
        name: 'file',
        formData: {
			name: '身份证',
			key: fileKey,
			policy: 'eyJleHBpcmF0aW9uIjoiMjMzNy0wNC0xM1QwMjo0MjoxMi40ODFaIiwiY29uZGl0aW9ucyI6W1siY29udGVudC1sZW5ndGgtcmFuZ2UiLDAsMTA0ODU3NjAwMF0sWyJzdGFydHMtd2l0aCIsIiRrZXkiLCJ1ZWRpdG9yL3VwbG9hZC93ZWl4aW4vIl1dfQ==',
			OSSAccessKeyId: 'Te5npXFe8IdIxPgQ',
			signature: 'I1Dv3FioQ4hoBh0ui2Rvsax+fAI=',
			success_action_status: "200"
		},
        success: (res) => {
			 let url="http://tuozhen1.oss-cn-beijing.aliyuncs.com/"+fileKey
			 console.log(url,123)
		     this.callWxOCR(url);    
          uni.showToast({ title: url ? '上传成功' : '上传失败' });
        },
        fail: () => uni.showToast({ title: '网络错误', icon: 'none' }),
        complete: () => (this.uploading = false),
        onProgressUpdate: e => (this.percent = e.progress)
      });
    },
	 /* 2.2 调微信官方 OCR 接口（后端转发，避免暴露 secret） */
	    async callWxOCR(imgUrl) {
			let usrUserId=uni.getStorageSync('usrUserId')
	      uni.request({
	        url: 'https://app.mzmzb.com/application-usrapp/mzmzb/idcardIdentify.tz?usrUserId='+usrUserId+'&imageUrl='+imgUrl, // 后端转发接口
	        method: 'POST',
	        // data: { imageUrl: imgUrl, usrUserId: usrUserId }, // Back 为反面
	        success: (res) => {
	          const data = res.data.result;
			  console.log(res,1)
			  console.log(res.data,2)
			  console.log(data,3)
	         let pages = getCurrentPages();
	         let prevPage = pages[pages.length-2]
	         prevPage.$vm.isBack = true
	         prevPage.$vm.userName = data.name
			 prevPage.$vm.idNo = data.id
			  const index = this.raceArray.findIndex(item => item.name.includes(data.race))
			 prevPage.$vm.raceIndex  = index
			 let isChildren=parseInt(data.age, 10)>18?0:1
			 prevPage.$vm.isChildren = isChildren
			 
	        },
	        complete: () => (this.loading = false)
	      });
	    },
		goback(){
			uni.navigateBack(-1)
		}
  }
};
</script>

<style scoped>
.container {
	padding: 50rpx 30rpx;
}

.text {
	font-size: 32rpx;
	font-weight: 400;
	color: rgba(77, 71, 71, 1);
}

.image-container {
	margin: auto;
	text-align: center;
	margin-top: 50rpx;
	width: 100%;
}

.image-container image {
	width: 100%;
}

.btn {
	margin-top: 80rpx;
	height: 88rpx;
	line-height: 88rpx;
	width: 100%;
	background: rgba(138, 97, 28, 1);
	border-radius: 44rpx;
	color: #FFFFFF;
	text-align: center;
	position: relative;
	z-index: 999;
}

.wrap{padding:40rpx}
button{margin-bottom:30rpx}
.preview{width:90%;border-radius:12rpx;margin:20rpx auto;display:block}
</style>